package com.im.common.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServer {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(9001);
        while (true) {
            System.out.println("等待连接....");
            Socket socket = serverSocket.accept(); // 阻塞方法
            System.out.println("有客户端连接....");
            new Thread(() -> {
                System.out.println("准备接收消息....");
                try (InputStream inputStream = socket.getInputStream();
                     OutputStream outputStream = socket.getOutputStream()) {
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        String message = new String(buffer, 0, len);
                        System.out.println("接收到信息: " + message);
                        String response = "Hello, " + message;
                        outputStream.write(response.getBytes());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
